package Controller;

// The Controller coordinates interactions


import Dao.LoginDao;
import Main.MainController;
import Model.Employee;
import Model.Login;
import View.LoginView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

// between the View and Model
public class LoginController {
    private Login loginModel = new Login() ;
    private LoginView loginView = new LoginView();
    private LoginDao loginDao = new LoginDao();
    MainController mc;

    //constructor
    public LoginController(MainController mainController){
        mc = mainController;
        /*
         * Tell the View that when ever the login button
	 * is clicked to execute the actionPerformed method
	 * in the LoginButtonListener inner class
         */
        this.loginView.addLoginButtonListener(new LoginButtonListener());
        this.loginView.addCancelButtonListener(new CancelButtonListener());
    }
    
    public class LoginButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            String userName, password;
            Employee emp;
            userName = loginView.getUserName();
            password = loginView.getPassword();
            
            //if user is on employee table get an Employee instance
            emp = loginDao.isUserAuthorized(userName, password);
            if( emp != null){
                mc.mainView.mainLoginB.setVisible(false);//login not visible
                mc.mainView.mainLogoutB.setVisible(true);//logout visible
                mc.mainView.mainOrderB.setEnabled(true);
                mc.mainView.mainSmpsB.setEnabled(true);
                mc.mainView.mainLogoL.setText("Welcome " + emp.getName());
                loginModel.setEmp(emp);
                //if employee classification = 1, normal user
                if(emp.getClassification() != 1) mc.mainView.mainAdminB.setEnabled(true);
                loginView.setUserNameTF(""); loginView.setPasswordTF("");
                loginView.dispose();//close the frame
            }else{//if user is not in employee table
                JOptionPane.showMessageDialog(null, "null employee!, LoginController");
            }
        }
    }
    
     public class CancelButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            loginView.setUserNameTF(""); loginView.setPasswordTF("");
            loginView.dispose(); //close frame
        }
    }
    
    public Login getLoginModel() {
        return loginModel;
    }

    public LoginView getLoginView() {
        return loginView;
    }

    public LoginDao getLoginDao() {
        return loginDao;
    }
    
    
}
